package com.aw.manual.ejemplo9;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * User: gmc
 * Date: 27/05/2010
 */
public class EntrevistaScope implements Scope {
    private static Map<String, Cuaderno> cuadernosDeEntrevista = new ConcurrentHashMap();
    private String id;

    public Object get(String name, ObjectFactory objectFactory) {
        if (!cuadernosDeEntrevista.containsKey(name)) {
            Cuaderno obj = (Cuaderno) objectFactory.getObject();
            cuadernosDeEntrevista.put(name, obj);
        }
        return cuadernosDeEntrevista.get(name);
    }

    public Object remove(String name) {
        return null;
    }

    public void registerDestructionCallback(String name, Runnable runnable) {
    }

    public Object resolveContextualObject(String name) {
        return null;
    }

    public String getConversationId() {
        return id;
    }

    public void inicializar() {
        System.out.println("Inicializar Scope");
        id = "" + new Date().getTime();
    }

    public void finalizar() {
        System.out.println("Finalizar Scope");
        grabarInformacionDeCuadernos();
        cuadernosDeEntrevista = new ConcurrentHashMap();
    }

    private void grabarInformacionDeCuadernos() {
        Collection<Cuaderno> cuadernos = cuadernosDeEntrevista.values();
        for (Cuaderno cuaderno : cuadernos) {
            System.out.println(cuaderno);
        }
    }
}
